﻿using AutomaticScrewLocking.domain.dataStorage.repository;
using AutomaticScrewLocking.infrastructure.pojo;
using AutomaticScrewLocking.infrastructure.repository;
using System;
using System.Collections.Generic;
using System.Data;

namespace AutomaticScrewLocking.domain.torque.dataStorage.service.impl
{
    class MySqlDataStorageServiceImpl : DataStorageService
    {
        private ITorqueRepository torqueRepository;

        public MySqlDataStorageServiceImpl()
        {
            this.torqueRepository = new TorqueRepository();
        }

        /// <summary>
        /// 存储最大扭力数据，保存到数据库
        /// </summary>
        /// <param name="maxTorque">最大扭力</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool SaveMaxTorqueData(double maxTorque, out string errorMsg)
        {
            bool result = false;
            errorMsg = string.Empty;
            try
            {
                int rows = torqueRepository.saveTorqueData(maxTorque, DateTime.Now);
                if(rows > 0)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }catch(Exception ex)
            {
                errorMsg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 根据时间获取历史扭力数据
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public List<double> getHistoryTorqueListByTime(DateTime startTime, DateTime endTime)
        {
            TorquePoJo torque = new TorquePoJo(startTime, endTime);
            DataSet dataSet = torqueRepository.queryTorqueList(torque);
            List<double> torqueValueList = new List<double>();
            if (dataSet != null && dataSet.Tables != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
            {

                for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                {
                    double torqueValue = dataSet.Tables[0].Rows[i].Field<double>("torque_value");
                    torqueValueList.Add(torqueValue);
                }
            }
            return torqueValueList;
        }
    }
}
